package cn.wit.summit.chwan.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.request.TopicListRequest;
import cn.wit.summit.chwan.models.response.DailyNewIndexResponse.TopAdBean;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.MyImageLoader;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import retrofit2.Retrofit;

public class SpecialGamesActivity extends BaseActivity {

    @Bind(R.id.bar_title_tx)
    TextView           barTitleTx;
    @Bind(R.id.recyclerView)
    RecyclerView       recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private GameAdapter adapter;

    List<TopAdBean> datas          = new ArrayList<>();
    int             belong_type_id = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        customHeader = true;
        setContentView(R.layout.activity_special_games);
        ButterKnife.bind(this);
        initApi();
        belong_type_id = getIntent().getIntExtra("belong_type_id", 0);
        String title = "";
        if (getIntent() != null) title = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(title)) title = "专题";

        barTitleTx.setText(title);

        initRecyclerView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initRecyclerView() {
        adapter = new GameAdapter(this, datas);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        recyclerView.setFocusable(false);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                loadSvr();
            }
        });
        refreshLayout.setOnLoadMoreListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadSvr();
            }
        });
        //触发自动刷新
        refreshLayout.autoRefresh();
    }

    //region loadSvr
    int pn = 1, pc = 20;

    void loadSvr() {
        TopicListRequest request = retrofitManager.getTopicList(belong_type_id, pn, pc);
        api.getTopicList(request).enqueue(new MyCallback<ResponseBase<List<TopAdBean>>>() {
            @Override
            public void onSuccess(ResponseBase<List<TopAdBean>> model) {
                if (model != null) {
                    if (model.getCode() == 600)
                        onResponse(model.getData_info());
                    else
                        onFailure(model.getCode(), model.getMsg());
                } else {
                    onFailure(-1, "服务器数据为空！");
                }

            }

            @Override
            public void onFailure(int code, String msg) {
                onFailure(new Exception(msg), code);
            }

            public void onResponse(List<TopAdBean> data) {
                cancelLoadingFinish();
                if (pn == 1) {
                    datas.clear();
                }
                if (data != null)
                    datas.addAll(data);
                if (data == null || data.size() == 0) {
                    stopLoading(true);
                } else {
                    stopLoading();
                    pn++;
                }

            }

            public void onFailure(Exception e, int code) {
                cancelLoadingError();
                stopLoading();
                showToast(e.getMessage());
            }
        });
    }

    private void stopLoading(boolean noMore) {
        if (noMore) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMoreWithNoMoreData();
            adapter.notifyDataSetChanged();
        } else
            stopLoading();
    }

    private void stopLoading() {
        if (refreshLayout!=null) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
        adapter.notifyDataSetChanged();
    }

    //endregion

    private static class GameAdapter extends RecyclerView.Adapter {
        private List<TopAdBean> datas;
        Context context;

        public GameAdapter(Context context, List<TopAdBean> datas) {
            this.context = context;
            this.datas = datas;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            if (viewType == 0) {

                View view = new View(context);
                int                       width  = ViewGroup.LayoutParams.MATCH_PARENT;
                int                       height = (int) context.getResources().getDimension(R.dimen.wdp19);
                RecyclerView.LayoutParams lp     = new RecyclerView.LayoutParams(width, height);
                view.setLayoutParams(lp);

                return new ItemHeader(view);
            }
            return new ImgVH(LayoutInflater.from(context).inflate(R.layout.item_special_game_img, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
            if (holder == null) return;
            if (getItemViewType(position) == 0) {
                return;
            }
            ImgVH h = (ImgVH) holder;
            MyImageLoader.load(h.img, getItem(position).getJump_cover_big_pic(), MyImageLoader.makeRoundParams(context, context.getResources().getDimensionPixelOffset(R.dimen.wdp8)));
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    IntentUtil.getInstance().goSpecialGameDetail(v.getContext(), getItem(position).getJump_info().getJump_link_type_val());
                }
            });
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0 || position == datas.size() + 1) return 0;
            return 1;
        }

        public TopAdBean getItem(int position) {
            if (datas == null) return null;
            if (position == 0 || position == datas.size() + 1) return null;
            return datas.get(position - 1);
        }

        @Override
        public int getItemCount() {
            if (datas == null) return 0;
            return datas.size() + 1;
        }

        private class ItemHeader extends RecyclerView.ViewHolder {

            public ItemHeader(View itemView) {
                super(itemView);
            }
        }

        private class ImgVH extends RecyclerView.ViewHolder {
            SimpleDraweeView img;

            public ImgVH(View inflate) {
                super(inflate);
                img = inflate.findViewById(R.id.img);
            }
        }
    }

    @OnClick(R.id.back)
    void back() {
        finish();
    }

    @Override
    public void reGetData() {
        if (NetWorkUtils.isNetworkConnected(this)) {
            pn = 1;
            loadSvr();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (datas != null && datas.size() > 0
                && !notNetEvent.isHasNet) return;
        super.onEventMainThread(notNetEvent);
    }

    //region Retrofit
    private RetrofitManager retrofitManager;
    private Retrofit        retrofit;
    private ApiUtil         api;

    void initApi() {
        if (retrofitManager == null) {
            retrofitManager = RetrofitManager.getInstance(this);
            retrofit = retrofitManager.getRetrofit();
            api = retrofit.create(ApiUtil.class);
        }
    }
    //endregion
}
